<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title>智能大棚环境监测系统</title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.css" rel="stylesheet" />
		<link href="../css/party.css" rel="stylesheet" />
		<link href="../css/home.css" rel="stylesheet" />
		<link href="../css/customize.css" rel="stylesheet" />
		<link href="../css/modern-unified.css" rel="stylesheet" />
	</head>

	<body>
		<div class="modern-container">
			<!-- 现代化头部 -->
			<div class="modern-header">
				<h1>智能大棚环境监测系统</h1>
				<div class="modern-status modern-status-success" id="deviceStatus">
					连接设备
				</div>
			</div>

			<!-- 功能菜单卡片 -->
			<div class="modern-card">
				<div class="modern-grid">
					<div class="modern-list-item" id="monitor">
						<div class="modern-icon">
							<img src="../image/monitor.png" alt="环境监测" style="width: 24px; height: 24px;">
						</div>
						<div class="modern-list-content">
							<div class="modern-list-title">环境监测</div>
							<div class="modern-list-subtitle">实时监测大棚环境数据</div>
						</div>
					</div>
					
					<div class="modern-list-item" id="fan">
						<div class="modern-icon">
							<img src="../image/fan.png" alt="手动排风" style="width: 24px; height: 24px;">
						</div>
						<div class="modern-list-content">
							<div class="modern-list-title">手动排风</div>
							<div class="modern-list-subtitle">控制大棚通风系统</div>
						</div>
					</div>
					
					<div class="modern-list-item" id="warning">
						<div class="modern-icon">
							<img src="../image/alert.png" alt="手动预警" style="width: 24px; height: 24px;">
						</div>
						<div class="modern-list-content">
							<div class="modern-list-title">手动预警</div>
							<div class="modern-list-subtitle">设置环境预警参数</div>
						</div>
					</div>
					
					<div class="modern-list-item" id="setting">
						<div class="modern-icon">
							<img src="../image/threshold.png" alt="参数设置" style="width: 24px; height: 24px;">
						</div>
						<div class="modern-list-content">
							<div class="modern-list-title">参数设置</div>
							<div class="modern-list-subtitle">配置监测阈值参数</div>
						</div>
					</div>
				</div>
			</div>

			<!-- 手动模式开关 -->
			<div class="modern-card">
				<div style="display: flex; justify-content: space-between; align-items: center;">
					<div>
						<div class="modern-list-title">手动模式</div>
						<div class="modern-list-subtitle">启用手动控制模式</div>
					</div>
					<div class="mui-switch" id="manualSwitch">
						<div class="mui-switch-handle"></div>
					</div>
				</div>
			</div>

			<!-- 监测数据展示 -->
			<div id="chartCard" style="display: none; margin-bottom: 20px;">
				<div class="modern-grid-2">
					<div class="modern-data-card">
						<div class="modern-data-value" id="temp">--</div>
						<div class="modern-data-label">温度 (°C)</div>
					</div>
					<div class="modern-data-card">
						<div class="modern-data-value" id="humi">--</div>
						<div class="modern-data-label">湿度 (%)</div>
					</div>
					<div class="modern-data-card">
						<div class="modern-data-value" id="smoke">--</div>
						<div class="modern-data-label">烟雾 (ppm)</div>
					</div>
					<div class="modern-data-card">
						<div class="modern-data-value" id="pm25">--</div>
						<div class="modern-data-label">PM2.5 (μg/m³)</div>
					</div>
				</div>
			</div>

			<!-- 阈值设置 -->
			<div class="modern-card" id="threshold" style="display: none;">
				<div class="modern-list-title" style="margin-bottom: 20px;">参数阈值设置</div>
				
				<!-- 测试按钮 -->
			<!-- 	<div style="margin-bottom: 16px; text-align: center;">
					<button class="modern-btn" id="testButton" style="margin: 0 8px;">测试按钮绑定</button>
					<button class="modern-btn" id="debugButton" style="margin: 0 8px;">调试信息</button>
				</div> -->
				
				<div style="margin-bottom: 16px;">
					<label class="modern-list-subtitle">温度阈值 (°C)</label>
					<div style="display: flex; align-items: center; gap: 12px; margin-top: 8px;">
						<button class="modern-btn-outline" id="tempSub" style="padding: 8px 16px;" onclick="console.log('温度减按钮点击'); var input = document.getElementById('tempThreshold'); var val = parseInt(input.value, 10) || 0; if (val > 1) { input.value = val - 1; } bluetoothTool && bluetoothTool.sendData(cmd.temp_threshold_sub);">-</button>
						<input type="number" class="modern-input" id="tempThreshold" style="flex: 1; text-align: center;" min="1" max="99">
						<button class="modern-btn-outline" id="tempAdd" style="padding: 8px 16px;" onclick="console.log('温度加按钮点击'); var input = document.getElementById('tempThreshold'); var val = parseInt(input.value, 10) || 0; if (val < 99) { input.value = val + 1; } bluetoothTool && bluetoothTool.sendData(cmd.temp_threshold_add);">+</button>
					</div>
				</div>
				
				<div style="margin-bottom: 16px;">
					<label class="modern-list-subtitle">湿度阈值 (%)</label>
					<div style="display: flex; align-items: center; gap: 12px; margin-top: 8px;">
						<button class="modern-btn-outline" id="humiSub" style="padding: 8px 16px;" onclick="console.log('湿度减按钮点击'); var input = document.getElementById('humiThreshold'); var val = parseInt(input.value, 10) || 0; if (val > 1) { input.value = val - 1; } bluetoothTool && bluetoothTool.sendData(cmd.humi_threshold_sub);">-</button>
						<input type="number" class="modern-input" id="humiThreshold" style="flex: 1; text-align: center;" min="1" max="99">
						<button class="modern-btn-outline" id="humiAdd" style="padding: 8px 16px;" onclick="console.log('湿度加按钮点击'); var input = document.getElementById('humiThreshold'); var val = parseInt(input.value, 10) || 0; if (val < 99) { input.value = val + 1; } bluetoothTool && bluetoothTool.sendData(cmd.humi_threshold_add);">+</button>
					</div>
				</div>
				
				<div style="margin-bottom: 16px;">
					<label class="modern-list-subtitle">烟雾阈值 (ppm)</label>
					<div style="display: flex; align-items: center; gap: 12px; margin-top: 8px;">
						<button class="modern-btn-outline" id="smokeSub" style="padding: 8px 16px;" onclick="console.log('烟雾减按钮点击'); var input = document.getElementById('smokeThreshold'); var val = parseInt(input.value, 10) || 0; if (val > 1) { input.value = val - 1; } bluetoothTool && bluetoothTool.sendData(cmd.smoke_threshold_sub);">-</button>
						<input type="number" class="modern-input" id="smokeThreshold" style="flex: 1; text-align: center;" min="1" max="200">
						<button class="modern-btn-outline" id="smokeAdd" style="padding: 8px 16px;" onclick="console.log('烟雾加按钮点击'); var input = document.getElementById('smokeThreshold'); var val = parseInt(input.value, 10) || 0; if (val < 200) { input.value = val + 1; } bluetoothTool && bluetoothTool.sendData(cmd.smoke_threshold_add);">+</button>
					</div>
				</div>
				
				<div>
					<label class="modern-list-subtitle">PM2.5阈值 (μg/m³)</label>
					<div style="display: flex; align-items: center; gap: 12px; margin-top: 8px;">
						<button class="modern-btn-outline" id="pm25Sub" style="padding: 8px 16px;" onclick="console.log('PM2.5减按钮点击'); var input = document.getElementById('pm25Threshold'); var val = parseInt(input.value, 10) || 0; if (val > 1) { input.value = val - 1; } bluetoothTool && bluetoothTool.sendData(cmd.pm25_threshold_sub);">-</button>
						<input type="number" class="modern-input" id="pm25Threshold" style="flex: 1; text-align: center;" min="1" max="500">
						<button class="modern-btn-outline" id="pm25Add" style="padding: 8px 16px;" onclick="console.log('PM2.5加按钮点击'); var input = document.getElementById('pm25Threshold'); var val = parseInt(input.value, 10) || 0; if (val < 500) { input.value = val + 1; } bluetoothTool && bluetoothTool.sendData(cmd.pm25_threshold_add);">+</button>
					</div>
				</div>
			</div>

			<!-- 新闻资讯 -->
			<div class="modern-card" style="margin-bottom: 20px;">
				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
					<div class="modern-list-title">新闻资讯</div>
					<button class="modern-btn-outline" id="moreNews" style="padding: 8px 16px; font-size: 14px;">
						更多 →
					</button>
				</div>
				
				<div id="newsList" class="modern-list">
					<!-- 新闻列表将通过JavaScript动态生成 -->
				</div>
			</div>

			<!-- 调试信息区域 -->
			<div class="modern-card" id="debugInfo" style="display: none;">
				<div class="modern-list-title" style="margin-bottom: 20px;">调试信息</div>
				<div id="debugContent" style="font-size: 12px; color: #7F8C8D;">
					<!-- 调试信息将在这里显示 -->
				</div>
			</div>
		</div>

		<div id="deviceLIst" class="mui-popover mui-popover-bottom mui-popover-action ">
			<!-- 可选择菜单 -->
			<ul id="deviceMenu" class="mui-table-view">
				<li class="mui-table-view-cell">
					<a href="#">请点击设备名连接</a>
				</li>
			</ul>
			<!-- 取消菜单 -->
			<ul class="mui-table-view">
				<li id="cancelSheet" class="mui-table-view-cell">
					<a href="#sheet1"><b>取消</b></a>
				</li>
			</ul>
		</div>

		<div id="notify" class="message" style="display: none;">
			<img class="ico" src="../image/msg-ico.png" />
			<div id="message" class="content"></div>
			<button id="closeMsg" class="mui-btn mui-btn-orange mui-btn-block">知道了</button>
		</div>

		<script src="../js/mui.js"></script>
		<script src="../js/bluetooth.js"></script>
		<script src="../js/request.js"></script>
		<script src="../js/storage.js"></script>
		<script src="../js/date.js"></script>
		<script src="../js/common.js"></script>
		<script src="../js/echarts.min.js"></script>
		<!--加载GPS组件-->
		<script src="../js/gps.js"></script>
		<script type="text/javascript">
			//声明全局变量
			let baseUrl = localStorage.getItem("ip");
			let deviceList = [];
			let newsList = [];
			let msg = "";
			//获取当前登录用户
			let user = userCache.getUser();
			//获取今天日期
			let today = parseTime(new Date());
			// 当前连接设备信息
			let device = {
				serialNo: '',
				status: '0',
				deviceType: '',
				registerDate: today,
			}
			let gpsLocation = {
				userId: user.userId,
				deviceNo: '',
				lng: null,
				lat: null,
				coordsType: '高德地图',
				dataTime: null,
			}
			let intervalId_1 = null;
			let intervalId_2 = null;
			let greenhouseList = [];
			let greenhouseId = null;
			// 测试使用
			// let greenhouseId = 3;
			let bleData = {
				temp: 0,
				smoke: 0,
				humi: 0,
				pm25: 0,
				tempThreshold: 0,
				pm25Threshold: 0,
				smokeThreshold: 0,
				humiThreshold: 0,
			}
			let control = {
				manual: false, //是否手动
				alert: false, //是否报警
				fan: false, //是否排风
			}
			//向设备发送的命令
			let cmd = {
				setting_on: [0x68, 0x0d, 0x0a], //开启设置：['h',0x0d,0x0a]
				setting_off: [0x69, 0x0d, 0x0a], //关闭设置：['i',0x0d,0x0a],
				manual_on: [0x61, 0x0d, 0x0a], //开启手动模式['a', 0x0d, 0x0a],
				manual_off: [0x62, 0x0d, 0x0a], //关闭手动模式：['b', 0x0d, 0x0a]
				fan_switch: [0x63, 0x0d, 0x0a], //排风开关：['c', 0x0d, 0x0a]
				alert_switch: [0x64, 0x0d, 0x0a], //播放/停止报警：['d', 0x0d, 0x0a]
				temp_threshold_sub: [0x6A, 0x0d, 0x0a], //温度阈值减：['j', 0x0d, 0x0a]
				temp_threshold_add: [0x6B, 0x0d, 0x0a], //温度阈值加：['k', 0x0d, 0x0a]
				smoke_threshold_sub: [0x6E, 0x0d, 0x0a], //烟雾阈值减：['n', 0x0d, 0x0a]
				smoke_threshold_add: [0x6F, 0x0d, 0x0a], //烟雾阈值加：['o', 0x0d, 0x0a]
				humi_threshold_sub: [0x6C, 0x0d, 0x0a], //湿度阈值减：['l', 0x0d, 0x0a]	
				humi_threshold_add: [0x6D, 0x0d, 0x0a], //湿度阈值加：['m', 0x0d, 0x0a]
				pm25_threshold_sub: [0x70, 0x0d, 0x0a], //PM2.5阈值减：['p', 0x0d, 0x0a]
				pm25_threshold_add: [0x71, 0x0d, 0x0a], //PM2.5阈值加：['q', 0x0d, 0x0a]
			}

			let bluetoothTool = null;
			let map = null;
			let marker = null;
			let gps = null;

			mui.init()
			mui.plusReady(function() {

				//初始化GPS工具
				gps = getGPS();
				gps.setOptions({
					getLocationCallback: (position) => {
						let lng = position.coords.longitude; //经度
						let lat = position.coords.latitude; //纬度
						console.log('获取位置信息回调', '坐标类型', position.coordsType, '纬度', lat, '经度', lng);
						gpsLocation.lng = lng;
						gpsLocation.lat = lat;
						saveLocation();
					},
					watchLocationCallback: (position) => {
						let lng = position.coords.longitude; //经度
						let lat = position.coords.latitude; //纬度
						console.log('实时获取位置信息回调', '坐标类型', position.coordsType, '纬度', lat, '经度', lng);
						gpsLocation.lng = lng;
						gpsLocation.lat = lat;
						saveLocation();
					}
				})

				gps.getCurrentPosition();

				//初始化蓝牙工具
				bluetoothTool = createBluetoothTool();
				let bluetoothStatus = bluetoothTool.state;

				bluetoothTool.init({
					listenBTStatusCallback: function(state) {
						msg = "蓝牙状态: " + state;
						console.log(msg)
					},
					discoveryDeviceCallback: function(newDevice) {
						console.log('发现新设备', newDevice.name, newDevice.address)
						if (!newDevice.name) {
							return;
						}
						let oldDev = deviceList.filter(item => item.address == newDevice.address);
						if (oldDev.length > 0) {
							console.log('旧设备无需添加', oldDev.address);
							return;
						}

						deviceList.push({
							title: newDevice.name,
							address: newDevice.address,
						});
						//动态添加设备列表
						appendDeviceList(newDevice);
					},
					discoveryFinishedCallback: function() {
						msg = "搜索完成";
					},
					cancelDiscoveryCallback: function() {
						msg = "停止搜索";
					},
					readDataCallback: function(dataByteArr) {
						// console.log('接收到数据', dataByteArr);
						parseBLEData(dataByteArr);
					},
					connExceptionCallback: function(e) {
						console.log(e);
						msg = "设备连接失败";
						disconnDevice();
					}
				});

				//解析蓝牙数据
				function parseBLEData(data) {
					let receiveDataArr = data instanceof Array ? data : [];
					const merged = new Uint8Array(receiveDataArr);
					let dataStr = new TextDecoder().decode(merged);
					console.log('蓝牙原始数据:', dataStr);

					// 解析温度
					let segment1 = dataStr.indexOf("A:");
					if ((segment1 != -1) && (dataStr.indexOf("#", segment1)) != -1) {
						bleData.temp = dataStr.substring(segment1 + 2, dataStr.indexOf("#", segment1));
					}
					// 解析湿度
					let segment2 = dataStr.indexOf("B:");
					if ((segment2 != -1) && (dataStr.indexOf("#", segment2)) != -1) {
						bleData.humi = dataStr.substring(segment2 + 2, dataStr.indexOf("#", segment2));
					}
					// 解析烟雾
					let segment3 = dataStr.indexOf("C:");
					if ((segment3 != -1) && (dataStr.indexOf("#", segment3)) != -1) {
						bleData.smoke = dataStr.substring(segment3 + 2, dataStr.indexOf("#", segment3));
					}
					// 解析PM2.5
					let segment4 = dataStr.indexOf("D:");
					if ((segment4 != -1) && (dataStr.indexOf("#", segment4)) != -1) {
						bleData.pm25 = dataStr.substring(segment4 + 2, dataStr.indexOf("#", segment4));
					}
					// 温度阈值
					let segment5 = dataStr.indexOf("E:");
					if ((segment5 != -1) && (dataStr.indexOf("#", segment5)) != -1) {
						bleData.tempThreshold = dataStr.substring(segment5 + 2, dataStr.indexOf("#", segment5));
					}
					// 湿度阈值
					let segment6 = dataStr.indexOf("F:");
					if ((segment6 != -1) && (dataStr.indexOf("#", segment6)) != -1) {
						bleData.humiThreshold = dataStr.substring(segment6 + 2, dataStr.indexOf("#", segment6));
					}
					// 烟雾阈值
					let segment7 = dataStr.indexOf("G:");
					if ((segment7 != -1) && (dataStr.indexOf("#", segment7)) != -1) {
						bleData.smokeThreshold = dataStr.substring(segment7 + 2, dataStr.indexOf("#", segment7));
					}
					// PM2.5阈值
					let segment8 = dataStr.indexOf("H:");
					if ((segment8 != -1) && (dataStr.indexOf("#", segment8)) != -1) {
						bleData.pm25Threshold = dataStr.substring(segment8 + 2, dataStr.indexOf("#", segment8));
					}

					// 刷新环境检测区
					document.getElementById('temp').innerHTML = bleData.temp + '℃';
					document.getElementById('humi').innerHTML = bleData.humi;
					document.getElementById('smoke').innerHTML = bleData.smoke;
					document.getElementById('pm25').innerHTML = bleData.pm25;

					// 刷新阈值输入框
					document.getElementById('tempThreshold').value = bleData.tempThreshold;
					document.getElementById('humiThreshold').value = bleData.humiThreshold;
					document.getElementById('smokeThreshold').value = bleData.smokeThreshold;
					document.getElementById('pm25Threshold').value = bleData.pm25Threshold;

					console.log('解析后数据:', JSON.stringify(bleData));
				}
				//动态添加设备列表
				function appendDeviceList(newDevice) {
					let menu = document.getElementById('deviceMenu');
					let li = document.createElement('li');
					li.className = 'mui-table-view-cell';
					li.addEventListener('tap', function(event) {
						connDevice(newDevice.address, newDevice.name);
					});
					li.innerHTML = '<a href="#">' + newDevice.name + '</a>';
					menu.append(li);
				}
				//连接蓝牙设备
				function connDevice(address, name) {
					let status = bluetoothTool.connDevice(address);
					device.serialNo = address;
					device.deviceType = name;
					if (status) {
						let statusElement = document.getElementById("deviceStatus");
						statusElement.innerHTML = "设备已连接";
						//缓存设备编号
						userCache.setDeviceNo(address);
						//更新设备状态
						updateDeviceStatus("1");
						//1秒同步显示一次数据
						clearInterval(intervalId_1);
						intervalId_1 = setInterval(synchDisplay, 200);
						clearInterval(intervalId_2);
						intervalId_2 = setInterval(getLatestExhaustMsg, 10000);
						//手动模式开关复位
						let isActive = document.getElementById("manualSwitch").classList.contains("mui-active");
						if (isActive) {
							mui('#manualSwitch').switch().toggle();
						}
						mui('#deviceLIst').popover('toggle');

						gps.getCurrentPosition();
					}
				}
				//发现蓝牙设备
				function discoveryNewDevice() {
					console.log('开始搜索设备')
					bluetoothTool.discoveryNewDevice();
				}

				//注册事件处理函数
				window.addEventListener('load', function(event) {
					// 调试：检查参数设置按钮是否存在
					setTimeout(() => {
						const thresholdButtons = ['tempSub', 'tempAdd', 'humiSub', 'humiAdd', 'smokeSub', 'smokeAdd', 'pm25Sub', 'pm25Add'];
						thresholdButtons.forEach(id => {
							const element = document.getElementById(id);
							console.log(`按钮 ${id} 存在:`, !!element);
						});
						// 页面加载时就绑定阈值按钮事件
						bindThresholdButtons();
					}, 1000);
				});
				window.addEventListener('refresh', function(event) {
					getNewsList();
					loadGreenhouseList();
				});
				window.addEventListener("unload", () => {
					console.log('关闭蓝牙连接');
					bluetoothTool.disConnDevice();
				})
				window.addEventListener("closeBLE", () => {
					let statusElement = document.getElementById("deviceStatus");
					if (statusElement.innerHTML == "连接设备") {
						console.log('关闭蓝牙连接');
						disconnDevice();
					}
				})

				document.querySelector('#cancelSheet').addEventListener('tap', function() {
					mui('#deviceLIst').popover('toggle');
				}, false);

				document.querySelector('#deviceStatus').addEventListener('tap', function() {
					let statusElement = document.getElementById("deviceStatus");
					if (statusElement.innerHTML.trim() == '连接设备') {
						plus.nativeUI.actionSheet({
							title: "选择大棚", //这里就是这个弹窗的title
							cancel: "取消", //取消按钮
							buttons: greenhouseList,
						}, function(bt) {
							/*actionSheet 按钮点击事件*/
							if (bt.index > 0) {
								greenhouseId = greenhouseList[bt.index - 1].greenhouseId;
								// 保存选择的大棚id到本地缓存
								console.log('保存选择的大棚id到本地缓存', greenhouseId)
								localStorage.setItem("greenhouseId", greenhouseId);
								discoveryNewDevice();
								mui('#deviceLIst').popover('toggle');
							}
						})
					} else {
						plus.nativeUI.confirm('确定断开设备连接', (event) => {
							console.log("点击确认对话框: " + event.index);
							if (event.index == 0) {
								disconnDevice();
							}
						});
					}
				}, false);
				
				//手动模式开关事件处理
				document.getElementById("manualSwitch").addEventListener("toggle", function(event) {
					let statusElement = document.getElementById("deviceStatus");
					if (statusElement.innerHTML.trim() == '连接设备') {
						plus.nativeUI.toast('请先连接设备');
					} else {
						if (event.detail.isActive) {
							let status = bluetoothTool.sendData(cmd.manual_on);
							if (status) {
								control.manual = true;
							}
						} else {
							let status = bluetoothTool.sendData(cmd.manual_off);
							if (status) {
								control.manual = false;
							}
						}
					}
				})
				
				//监测按钮事件处理
				document.querySelector('#monitor').addEventListener('tap', function() {
					let statusElement = document.getElementById("deviceStatus");
					if (statusElement.innerHTML.trim() == '连接设备') {
						plus.nativeUI.toast('请先连接设备');
					} else {
						let chCard = document.getElementById('chartCard');
						let stCard = document.getElementById('threshold');
						if (chCard.style.display == 'none') {
							stCard.style.display = 'none';
							chCard.style.display = 'block';
						} else {
							chCard.style.display = 'none';
						}
					}
				}, false);
				//报警事件处理
				document.querySelector('#warning').addEventListener('tap', function() {
					var isActive = document.getElementById("manualSwitch").classList.contains("mui-active");
					if (isActive) {
						let status = bluetoothTool.sendData(cmd.alert_switch);
						if (status) {
							control.alert = !control.alert;
							if (control.alert) {
								sendAlert('2');
							}
						}
					} else {
						plus.nativeUI.toast('请先开启手动模式');
					}
				}, false);

				//排风按钮事件处理
				document.querySelector('#fan').addEventListener('tap', function() {
					var isActive = document.getElementById("manualSwitch").classList.contains("mui-active");
					if (isActive) {
						controlRemoteFan();
					} else {
						plus.nativeUI.toast('请先开启手动模式');
					}
				}, false);

				//设置按钮事件处理
				document.querySelector('#setting').addEventListener('tap', function() {
					let statusElement = document.getElementById("deviceStatus");
					if (statusElement.innerHTML.trim() == '连接设备') {
						plus.nativeUI.toast('请先连接设备');
					} else {
						let chCard = document.getElementById('chartCard');
						let stCard = document.getElementById('threshold');
						if (stCard.style.display == 'none') {
							initThreshold();
							chCard.style.display = 'none';
							stCard.style.display = 'block';
							bluetoothTool.sendData(cmd.setting_on); //向设备发送设置阈值命令
							// 重新绑定+/-按钮事件
							bindThresholdButtons();
						} else {
							stCard.style.display = 'none';
							bluetoothTool.sendData(cmd.setting_off); //向设备发送设置阈值命令
						}
					}
				}, false);

				//初始化阈值
				function initThreshold() {
					if (bleData.humiThreshold > 0) {
						document.getElementById('humiThreshold').value = bleData.humiThreshold;
					}
					if (bleData.tempThreshold > 0) {
						document.getElementById('tempThreshold').value = bleData.tempThreshold;
					}
					if (bleData.pm25Threshold > 0) {
						document.getElementById('pm25Threshold').value = bleData.pm25Threshold;
					}
					if (bleData.smokeThreshold > 0) {
						document.getElementById('smokeThreshold').value = bleData.smokeThreshold;
					}
				}

				//绑定阈值调整按钮事件
				function bindThresholdButtons() {
					const buttons = [
						{id: 'tempSub', cmd: cmd.temp_threshold_sub},
						{id: 'tempAdd', cmd: cmd.temp_threshold_add},
						{id: 'humiSub', cmd: cmd.humi_threshold_sub},
						{id: 'humiAdd', cmd: cmd.humi_threshold_add},
						{id: 'smokeSub', cmd: cmd.smoke_threshold_sub},
						{id: 'smokeAdd', cmd: cmd.smoke_threshold_add},
						{id: 'pm25Sub', cmd: cmd.pm25_threshold_sub},
						{id: 'pm25Add', cmd: cmd.pm25_threshold_add}
					];
					buttons.forEach(btn => {
						const el = document.getElementById(btn.id);
						if (el) {
							el.onclick = null; // 先移除旧的
							el.onclick = function() {
								bluetoothTool.sendData(btn.cmd);
							};
						}
					});
				}

				//新闻更多连接事件处理
				document.querySelector('#moreNews').addEventListener('tap', function() {
					let statusElement = document.getElementById("deviceStatus");
					if (statusElement.innerHTML == "连接设备") {
						disconnDevice();
					}
					mui.openWindow({
						url: 'news.html',
						id: 'news',
						createNew: true,
						show: {
							autoShow: true,
							aniShow: 'slide-in-right',
							duration: 300
						},
						waiting: {
							autoShow: false
						}
					});
				}, false);

				//获取新闻列表
				getNewsList();
			})
			
			// 控制远程设备风扇开启/关闭
			function controlRemoteFan(){
				let status = bluetoothTool.sendData(cmd.fan_switch);
				if (status) {
					control.fan = !control.fan;
					if (control.fan) {
						saveExhaustRecord(null, '开启', null)
					} else {
						saveExhaustRecord(null, '关闭', null)
					}
				}
			}

			//断开蓝牙设备连接
			function disconnDevice() {
				bluetoothTool.disConnDevice();
				greenhouseId = null;
				let statusElement = document.getElementById("deviceStatus");
				statusElement.innerHTML = "连接设备";
				updateDeviceStatus("0");
				if (intervalId_1) {
					clearInterval(intervalId_1);
				}
				if (intervalId_2) {
					clearInterval(intervalId_2);
				}
				//清除设备编号缓存
				userCache.removeDeviceNo();
				//手动模式开关复位
				let isActive = document.getElementById("manualSwitch").classList.contains("mui-active");
				if (isActive) {
					mui('#manualSwitch').switch().toggle();
				}
			}

			//更新设备状态到后台
			function updateDeviceStatus(status) {
				device.status = status;
				console.log('更新设备状态到后台', device.serialNo)
				request.post('/api/device/status', device, (data) => {
					//提交成功回调
					console.log('调用服务端更新设备状态成功');
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端更新设备状态失败', error)
				})
			}

			//获取新闻列表
			function getNewsList() {
				console.log('获取新闻列表')
				//获取新闻列表
				request.get('/system/article/list', {
						pageNum: 1,
						pageSize: 3,
						orderByColumn: 'create_time',
						isAsc: 'desc'
					},
					(data) => {
						renderNewsList(data.rows)
					},
					(error, thrown) => {

					}
				);
			}
			//渲染新闻列表
			function renderNewsList(rows) {
				newsList = [...rows]
				let inHtml = ""
				for (let i = 0; i < newsList.length; i++) {
					// 判断cover是否有值，否则用默认图片
					let imgSrc = newsList[i].cover ? (baseUrl + newsList[i].cover) : '../image/default-news.png';
					var html = `<div class="news-list-item">
									<img src="${imgSrc}" alt="" style="width: 48px; height: 48px; border-radius: 12px; object-fit: cover;">
									<div class="modern-list-content">
										<div class="modern-list-title">${newsList[i].title}</div>
										<div class="modern-list-subtitle">${newsList[i].createTime}</div>
									</div>
									<div style="color: #95A5A6;">→</div>
								</div>`
					inHtml += html;
				}
				document.getElementById('newsList').innerHTML = inHtml
				var listView = document.getElementById('newsList');
				var listItem = document.getElementsByClassName('news-list-item');
				var clickEvent = function(i) {
					listItem[i].addEventListener('tap', function(event) {
						let statusElement = document.getElementById("deviceStatus");
						if (statusElement.innerHTML == "连接设备") {
							disconnDevice();
						}
						mui.openWindow({
							url: 'newsDetail.html',
							id: 'newsDetail.html',
							createNew: false,
							show: {
								autoShow: true,
							},
							extras: {
								// 传递的数据
								newsId: newsList[i].id
							}
						});

					});
				}
				//第三步就是用for循环，执行上面的clickEvent函数。for循环的循环次数就是列表的条目数量。
				for (var i = 0; i < listView.childElementCount; i++) {
					clickEvent(i);
				}
			}

			//获取大棚列表
			function loadGreenhouseList() {
				greenhouseList = [];
				let data = {}
				request.get('/system/greenhouse/list', data, (data) => {
					//提交成功回调
					console.log('调用服务端获取大棚信息成功');
					let list = data.rows;
					list.forEach(row => {
						let id = row.id;
						let name = row.name;
						greenhouseList.push({
							greenhouseId: id,
							title: name,
						})
					});
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端获取大棚信息失败', error);
				})
			}

			//上传监测数据到服务器
			function saveData() {
				let data = {
					ghId: greenhouseId,
					smoke: bleData.smoke,
					humility: bleData.humi,
					pm25: bleData.pm25,
					deviceNo: device.serialNo,
					temperature: bleData.temp,
				}
				submitMonitorData(data);
			}
			//提交数据
			function submitMonitorData(postData) {
				console.log('提交监测数据', JSON.stringify(postData))
				request.post('/api/greenhouse/monitor', postData, (data) => {
					//提交成功回调
					// console.log('调用服务端更新大棚监测数据成功');
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端更新大棚监测数据失败', error)
				})
			}

			//保存当前位置信息到后台
			function saveLocation() {
				if (!greenhouseId) {
					return;
				}
				let postData = {
					id: greenhouseId,
					lng: gpsLocation.lng,
					lat: gpsLocation.lat,
				}
				console.log('提交位置数据', JSON.stringify(postData))
				request.post('/api/greenhouse/location', postData, (data) => {
					//提交成功回调
					console.log('调用服务端更新位置数据成功');
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端更新位置数据失败', error)
				})
			}

			//发送预警信息: 1自动 2手动
			function sendAlert(type) {
				let msg = '';
				//温度异常
				if (bleData.temp * 1 > bleData.tempThreshold * 1) {
					msg = msg + '温度异常，阈值：' + bleData.tempThreshold + '<br/>';
				}
				//humi异常
				if (bleData.humi * 1 > bleData.humiThreshold * 1) {
					msg = msg + '湿度异常，阈值：' + bleData.humiThreshold + '<br/>';
				}
				//烟雾异常
				if (bleData.smoke * 1 > bleData.smokeThreshold * 1) {
					msg = msg + '烟雾异常，阈值：' + bleData.smokeThreshold + '<br/>';
				}
				//PM2.5异常
				if (bleData.pm25 * 1 > bleData.pm25Threshold * 1) {
					msg = msg + 'PM2.5异常，阈值：' + bleData.pm25Threshold + '<br/>';
				}
				//手动模式
				if (type == '2') {
					saveAlert(type, msg);
				} else {
					if (msg != '') {
						saveAlert(type, msg);
					}
				}
			}

			//保存预警数据
			function saveAlert(type, msg) {
				let postData = {
					ghId: greenhouseId,
					smoke: bleData.smoke,
					humility: bleData.humi,
					pm25: bleData.pm25,
					deviceNo: device.serialNo,
					temperature: bleData.temp,
					type: type,
					alert: msg,
				}

				console.log('提交监测预警数据', JSON.stringify(postData))
				request.post('/api/greenhouse/alert', postData, (data) => {
					//提交成功回调
					// console.log('调用服务端更新大棚监测预警数据成功');
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端更新大棚监测预警数据失败', error)
				})
			}

			//同步数据
			function synchDisplay() {
				document.getElementById('temp').innerHTML = bleData.temp + '℃';
				document.getElementById('humi').innerHTML = bleData.humi;
				document.getElementById('smoke').innerHTML = bleData.smoke;
				document.getElementById('pm25').innerHTML = bleData.pm25;

				saveData();

				sendAlert('1');
			}
			//获取最新的排风消息
			function getLatestExhaustMsg() {
				if (!greenhouseId) {
					return;
				}
				request.get('/api/msg/exhaust/' + greenhouseId, {},
					(resp) => {
						console.log('调用服务端获取最新的排风消息成功')
						let msg = resp.data;
						if (msg) {
							let category = msg.category;
							if (category === '1') { //开启排风
								console.log('接收到开启排风消息')
								sendNotify('请注意：该开启排风了！！！')
								let status = bluetoothTool.sendData(cmd.manual_on);
								if (status) {
									control.manual = true;
									controlRemoteFan()
								}
							}
							if (category === '2') { //关闭排风
								console.log('接收到关闭排风消息')
								sendNotify('请注意：该关闭排风了！！！')
								let status = bluetoothTool.sendData(cmd.manual_on);
								if (status) {
									control.manual = true;
									controlRemoteFan()
								}
							}
						}
					},
					(error, thrown) => {
						console.error('调用服务端获取最新的排风消息失败', error)
					}
				);
			}
			//保存排风记录
			function saveExhaustRecord(scheduleId, action, duration) {
				let data = {
					scheduleId,
					greenhouseId,
					action,
					duration,
				}
				request.post('/system/exhaustRecord', data, (resp) => {
					//提交成功回调
					console.log('调用服务端保存排风记录成功');
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端保存排风记录失败', error)
				})
			}
			
			var mask = mui.createMask(null);//callback为用户点击蒙版时自动执行的回调；
			
			document.querySelector('#closeMsg').addEventListener('tap', function() {
				let notify = document.getElementById('notify');
				notify.style.display = 'none';
				mask.close();//关闭遮罩
			}, false);
			
			//发送通知
			function sendNotify(msg) {
				// plus.push.setAutoNotification(true); //系统通知
				// plus.push.createMessage('提醒', null, {
				// 	delay: 1,
				// 	cover: true,
				// 	title: msg,
				// });
				// mui.toast(msg); //应用内通知
				let notify = document.getElementById('notify');
				let message = document.getElementById('message');
				message.innerHTML = msg;
				notify.style.display = '';
				mask.show();//显示遮罩
			}
			// 测试使用
			// clearInterval(intervalId_2);
			// intervalId_2 = setInterval(getLatestExhaustMsg, 10000);
			
			loadGreenhouseList();
		</script>
	</body>

</html>